import { useModel } from 'umi';
import { StorageKey } from '@/constants/storage-key';
import { useRequest } from 'ahooks';
import { Typography, Drawer, Table, Empty, TableColumnProps } from 'antd';
import { isEmpty, mergeWith } from 'lodash-es';
import { useState } from 'react';
import moment from 'moment';

const title = '物料操作记录';

export function ShowLog() {
  const [open, setOpen] = useState(false);
  function onClick() {
    setOpen(true);
  }
  function onCancel() {
    setOpen(false);
  }
  const { order } = useModel('bom');
  const orderId = order?.orderId;
  const { loading, data: logDetails } = useRequest(
    async () => {
      if (!open || !orderId) return;
      return await getBomSaveLogData(orderId);
    },
    { refreshDeps: [orderId, open] },
  );

  return (
    <>
      <Typography.Link onClick={onClick} className="float-right">
        {title}
      </Typography.Link>
      <Drawer
        width={'80%'}
        title={title}
        open={open}
        onClose={onCancel}
        loading={loading}
      >
        {logDetails &&
          (isEmpty(logDetails) ? (
            <Empty />
          ) : (
            <LogTable dataSource={logDetails} />
          ))}
      </Drawer>
    </>
  );
}

const columnCommonProps: TableColumnProps<any> = {
  width: 100,
  ellipsis: { showTitle: false },
  render: (value) => (
    <Typography.Text ellipsis={{ tooltip: value }}>{value}</Typography.Text>
  ),
};
const columns: TableColumnProps<BomSaveLogDetail>[] = [
  {
    title: '物料名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '物料编码',
    dataIndex: 'code',
    key: 'code',
  },
  {
    title: '物料型号',
    dataIndex: 'modelId',
    key: 'modelId',
  },
  {
    title: '操作时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    render: (value) => moment(value).format('YYYY-MM-DD HH:mm'),
  },
  {
    title: '操作人',
    dataIndex: 'userName',
    key: 'userName',
  },
];
columns.forEach((column) => {
  mergeWith(column, columnCommonProps, (value, srcValue, key) => {
    if (key === 'render' && value) {
      const render = value;
      const wrapRender = srcValue;
      return (...args: any[]) => wrapRender(render(...args));
    }
  });
});
function LogTable({
  loading,
  dataSource,
}: {
  loading?: boolean;
  dataSource?: BomSaveLogDetail[];
}) {
  return (
    <Table
      rowKey={'updateTime'}
      loading={loading}
      columns={columns}
      dataSource={dataSource}
      scroll={{ y: 500 }}
      pagination={false}
    />
  );
}

interface BomSaveLogDetail {
  userId: string;
  userName: string;
  modelId: string;
  code: string;
  name: string;
  updateTime: number;
}
export const getBomSaveLogKey = (orderId: string) =>
  `${StorageKey.BomReset}/orderId/${orderId}`;

export const getBomSaveLogData = async (orderId: string) =>
  (await Manycore.Storage.Enterprise.getItemAsync(getBomSaveLogKey(orderId)))
    ?.result as Promise<BomSaveLogDetail[]>;

export const setBomSaveLogData = async ({
  orderId,
  detail,
}: {
  orderId: string;
  detail: BomSaveLogDetail;
}) => {
  let details = await getBomSaveLogData(orderId);
  if (isEmpty(details)) {
    details = [detail];
  } else {
    details.push(detail);
  }
  return Manycore.Storage.Enterprise.putItemAsync({
    key: getBomSaveLogKey(orderId),
    value: { result: details },
  });
};
